package apis

import (
	"k8sops/pkg/services"
	"k8sops/pkg/services/agents"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

type JsonData struct {
	NodeName        string `json:"nodeName"`
	Namespace       string `json:"namespace"`
	SpecStatus      string `json:"specStatus"`
	SourceNamespace string `json:"sourceNamespace"`
	TargetNamespace string `json:"targetNamespace"`
}

func DealWithNodes(c *gin.Context) {
	n, err := services.GetNodes()
	if err != nil {
		log.Fatal(err)
		return
	}

	// 遍历节点并处理异常
	nodes := make(map[string][]string, 0)
	for _, node := range n.Items {
		for _, condition := range node.Status.Conditions {
			if condition.Type == "Ready" && condition.Status != "True" {
				// 节点NotReady处理
				nodes["NotReady"] = append(nodes["NotReady"], node.Name)
			}
			if condition.Type == "Ready" && condition.Status == "True" {
				nodes["Ready"] = append(nodes["Ready"], node.Name)
			}
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": nodes,
	})
}

func NodeAgentCleanDisk(c *gin.Context) {
	var (
		msg      map[string]string
		err      error
		jsonData JsonData
	)

	msg = make(map[string]string)

	err = c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "json data error",
		})
		return
	}

	err = agents.CleanNodeDisks(jsonData.NodeName)
	if err != nil {
		msg["OpsAgentCleanDisk"] = err.Error()
	} else {
		msg["OpsAgentCleanDisk"] = "clean node disk success"
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": msg,
	})
}
